package com.wzj.yygh.hosp.controller.admin;

import com.wzj.yygh.common.exception.YyghException;
import com.wzj.yygh.common.result.R;
import com.wzj.yygh.common.result.ResultCode;
import com.wzj.yygh.hosp.service.DoctorService;
import com.wzj.yygh.model.hosp.Doctor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Api(tags = "医生信息设置")
@RestController
@RequestMapping("/admin/hosp/doctor")
public class DoctorController {

    @Value("${file.root.path}")
    private String filePath;
    @Autowired
    private DoctorService doctorService;

    @GetMapping("findAll")
    public R findAllHospitalSet() {
        //调用service的方法
        List<Doctor> list = doctorService.list();
        return R.ok().data("list",list);
    }

    @ApiOperation("添加医生")
    @PostMapping("saveDoctorSet")
    public R saveDoctorSet(@RequestBody Doctor doctorInfo) {
        //调用service
        boolean save = doctorService.save(doctorInfo);
        if(save) {
            return R.ok().message("添加成功");
        } else {
            return R.error().message("添加失败");
        }
    }

    @ApiOperation("根据ID获取医生信息")
    @GetMapping("getDoctorSet/{id}")
    public R getDoctorSet(@PathVariable Long id) {

        Doctor doctorInfo = doctorService.getById(id);
        return R.ok().data("item",doctorInfo);
    }

    @ApiOperation("修改医生信息")
    @PutMapping("updateDoctorSet")
    public R updateDoctorSet(@RequestBody Doctor doctorInfo) {
        boolean flag = doctorService.updateById(doctorInfo);
        if(flag) {
            return R.ok().message("修改成功");
        } else {
            return R.error().message("修改失败");
        }
    }

    @ApiOperation(value = "逻辑删除医生信息")
    @DeleteMapping("{id}")
    public R removeDoctor(
            @ApiParam(value = "医生id",required = true)
            @PathVariable Long id) {
        try {
            boolean flag = doctorService.removeById(id);
            if(flag) {
                return R.ok().message("删除成功");
            } else {
                return R.error().message("删除失败").code(ResultCode.ERROR_DELETE);
            }
        } catch (Exception e) {
            throw new YyghException(ResultCode.ERROR,"删除医生信息错误",e);
        }
    }

    @ApiOperation("批量删除医生")
    @DeleteMapping("batchRemove")
    public R batchRemoveDoctor(@RequestBody List<Long> idList) {
        boolean result = doctorService.removeByIds(idList);
        if (result){
            return R.ok().message("删除成功");
        }else {
            return R.error().message("删除失败");
        }
    }

    @ApiOperation("文件上传本地")
    @PostMapping("uploadLocal")
    public R fileUpload(@RequestParam("file") MultipartFile file) {
        //获取上传文件名称
        String filename = file.getOriginalFilename();
        assert filename != null;
        String newFileName = UUID.randomUUID().toString().replaceAll("-","") + filename.substring(filename.lastIndexOf("."));
        //得到文件保存的位置以及新文件名
        File dest = new File(filePath);
        //文件夹不存在则创建
        if (!dest.exists()) {
            dest.mkdirs();
        }
        try {
            //上传文件保存
            file.transferTo(new File(dest+ "/" +newFileName));
            //文件URL路径地址
            return R.ok().message("文件上传成功").data("url","http://127.0.0.1:8201/admin/hosp/doctor/download?name="+newFileName);

        } catch (IOException e) {
            throw new YyghException(ResultCode.ERROR,"文件上传失败",e);
        }
    }

    @ApiOperation("文件下载")
    @GetMapping("/download")
    public void download(HttpServletResponse response, String name) {
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(filePath+ "/" + name);
            //输出流 通过输出流将文件写回游览器 展示照片
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new YyghException(ResultCode.ERROR,"文件未找到",e);
        }
    }

}
